package com.zoe.thread.th02_企业写法;

import java.util.concurrent.TimeUnit;

/**
 * @Author Zoe
 * @Date: 2021/04/30
 * @Description
 */
// 资源类
class Ticket01 {
    public int number = 30;

    public synchronized void sale() {
        if (number > 0) {
            System.out.println(Thread.currentThread().getName() + "  线程名卖出第：" + number-- + " 张票；还剩下：" + number);
        }
    }
}

/**
 * 线程           操作（资源类对外暴露的调用方法）           资源类
 */
public class SaleTicketSynchronize {
    public static void main(String[] args) {
        Ticket01 ticket = new Ticket01();

        // 匿名内部类操作资源类
        new Thread((new Runnable() {
            @Override
            public void run() {

            }
        }), "售票员1").start();

        // java8 Lambda表达式写法
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                try {
                    ticket.sale();
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, "售票员2").start();

    }
}
